package com.lqk.demo.concurrencytools.threadpool.executors.tasksubmit;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author lqk
 * @date 2022/1/7 15:44
 *
 *
 * 提交 tasks 中所有任务
 * <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
 *  throws InterruptedException;
 * 提交 tasks 中所有任务，带超时时间
 * <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
 *  long timeout, TimeUnit unit)
 *  throws InterruptedException;
 */
@Slf4j
public class TestInvokeAll {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(2);

        List<Future<String>> futures = pool.invokeAll(Arrays.asList(
                () -> {
                    log.debug("begin");
                    Thread.sleep(1000);
                    return "1";
                },
                () -> {
                    log.debug("begin");
                    Thread.sleep(500);
                    return "2";
                },
                () -> {
                    log.debug("begin");
                    Thread.sleep(2000);
                    return "3";
                }
        ));

        futures.forEach(v->{
            try {
                log.debug(v.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}
